<template>
    <div>
        <a-card v-if="hasSearchFields">
            <a-form layout="inline" :model="formSearch" @finish="handleFinish">
                <slot name="search" :form="formSearch" />

                <a-form-item>
                    <a-button type="primary" html-type="submit">
                        搜索
                    </a-button>
                </a-form-item>
            </a-form>
        </a-card>
        
        <a-card :title="title">
            <template #extra>
                <a-space>
                    <slot name="button" />
                    <a-button @click="handleFinish({})" size="small">
                        <icon name="ant-icon-ReloadOutlined" size="12px" />
                    </a-button>

                    <!-- 字段显示 -->
                    
                </a-space>
            </template>
            <a-table @change="handleTableChange" :columns="columns" :data-source="data?.lists"
                :loading="loading" :pagination="pagination" :row-key="props.rowKey" :expandable="{
                    ...props.expandable,
                    childrenColumnName: 'children'
                }">
                <template #emptyText>
                    <a-empty :description="error ?? emptyText.description" />
                </template>

                <template #bodyCell="{ column, record }">
                    <slot :name="column.dataIndex" :record="record"></slot>
                </template>
            </a-table>
        </a-card>

    </div>
</template>

<script setup lang="ts">
import type { TableProps, TablePaginationConfig } from 'ant-design-vue';
import { usePagination } from 'vue-request'
import type { FormProps } from 'ant-design-vue';

interface Data {
    lists?: any[]
    total?: number
    page?: number
    pageSize?: number
}

interface Props {
    columns: any[]          // 列
    data?: Data,            // 数据
    rowKey?: string         // 行key
    formSearch?: any,       // 搜索表单
    api?: (params: any) => Promise<any>  // 接口api
    title: string | boolean
    init?: boolean,
    emptyText?: {
        description: string
    },
    loading?: boolean,
    expandable?: {
        expandedRowRender?: (record: any) => any
        rowExpandable?: (record: any) => boolean
        childrenColumnName?: string
    },
    pagination?: boolean | object
}



const props = withDefaults(defineProps<Props>(), {
    columns: () => [],
    rowKey: () => 'id',
    formSearch: () => ({}),
    data: () => ({
        lists: [],
        total: 0,
        page: 1,
        pageSize: 10
    }),
    api: () => Promise.resolve({}),
    init: true,
    title: false,
    emptyText: () => ({
        description: '暂无数据'
    }),
    loading: false,
    expandable: () => ({
        rowExpandable: (record: any) => !!record.children?.length,
        childrenColumnName: 'children'
    }),
    pagination: true
})

const isComponentMounted = ref(false)

const { data, run, loading, refresh, error } = usePagination(
    (params) => {
        if (!props.api || props.api.name == 'default') {
            // 处理本地数据
            const { current = 1, pageSize = 10 } = params
            const start = (current - 1) * pageSize
            const end = start + pageSize
            const lists = props.data?.lists?.slice(start, end) || []
            
            return Promise.resolve({
                lists,
                total: props.data?.lists?.length || 0,
                current,
                pageSize
            })
        }
        return props.api({
            ...params,
            ...props.formSearch
        })
    },
    {
        defaultParams: [
            {
                current: 1,
                pageSize: 10
            }
        ]
    }
)


const pagination = computed(() => {
    if (props.pagination === false) return false
    if (typeof props.pagination === 'object') return props.pagination
    return {
        total: data.value?.total ?? 0,
        current: data.value?.current ?? 1,
        pageSize: data.value?.pageSize ?? 10
    }
})

onMounted(() => {
    isComponentMounted.value = true
})

onUnmounted(() => {
    isComponentMounted.value = false
})

const handleFinish: FormProps['onFinish'] = (values) => {
    // 点击搜索时，重置到第一页并刷新数据
    run({
        current: 1,
        pageSize: 10
    })
};

const handleTableChange: TableProps['onChange'] = (
    pagination: TablePaginationConfig,
    filters: Record<string, any>,
    sorter: any,
) => {
    if (!isComponentMounted.value) return
    run({
        current: pagination.current ?? 1,
        pageSize: pagination.pageSize ?? 10
    })
}

// 检查是否有搜索字段
const hasSearchFields = computed(() => {
    return Object.keys(props.formSearch).length > 0
})


// 暴露方法给父组件
defineExpose({
    run: (params?: any) => {
        run({
            current: data.value?.current ?? 1,
            pageSize: data.value?.pageSize ?? 10,
            ...params
        })
    },
    refresh
})
</script>
